//
//  JMCommonMethod.m
//  JMBaseProject
//
//  Created by Liuny on 2018/8/23.
//  Copyright © 2018年 liuny. All rights reserved.
//

#import "JMCommonMethod.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <CoreServices/CoreServices.h>
#import "SuperTabBarViewController.h"
@implementation JMCommonMethod

+(NSMutableAttributedString *)navigationTitleWithColor:(UIColor *)color title:(NSString *)title{
    NSMutableAttributedString *rtn = [[NSMutableAttributedString alloc] initWithString:title];
    UIFont *font = [UIFont boldSystemFontOfSize:19.0];
    [rtn addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, title.length)];
    [rtn addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, title.length)];
    return rtn;
}
+(void)navigationItemSet:(UIButton *)item fontColor:(UIColor *)color{
    [item setTitleColor:color forState:UIControlStateNormal];
    item.titleLabel.font = [UIFont boldSystemFontOfSize:15.0];
    [item setTitleColor:color forState:UIControlStateNormal];
    UIColor *disableColor = [UIColor colorWithRGB:color.rgbValue alpha:0.2];
    [item setTitleColor:disableColor forState:UIControlStateDisabled];
}

+(NSMutableDictionary *)baseRequestParams{
    NSMutableDictionary *rtn = [[NSMutableDictionary alloc] init];
    NSString *sessionId = [JMProjectManager sharedJMProjectManager].loginUser.sessionId;
    [rtn setJsonValue:sessionId key:@"sessionId"];
    return rtn;
}

//网络请求图片
//网络请求图片
+(NSURL *)imageUrlWithPath:(NSString *)imagePath{
    NSURL *rtn;
    if(![imagePath isKindOfClass:[NSString class]])
    {
        return rtn;;
    }
    if(imagePath.length == 0){
        return rtn;
    }
    NSString *path = imagePath;
    if(![imagePath hasPrefix:@"http"]){
        path = [ImageBaseUrl stringByAppendingPathComponent:imagePath];
    }
    NSString *url = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    rtn = [NSURL URLWithString:url];
    return rtn;
}

+(NSString *)pinImagePath:(NSString *)path{
    NSString *rtn;
    if(path.length == 0){
        return @"";
    }
    if(![path hasPrefix:@"http"]){
        NSString *allPath = [ImageBaseUrl stringByAppendingString:path];
        rtn = [allPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }else{
        rtn = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    return rtn;
}

+(void)shadowView:(UIView *)view{
    //阴影
    view.layer.shadowColor = [UIColor blackColor].CGColor;
    view.layer.shadowOffset = CGSizeMake(0, 5);
    view.layer.shadowOpacity = 0.04;
    //    view.layer.shadowRadius = 5;
}

//UITextField占位文字颜色
+(void)placeholderColor:(UITextField *)textField{
    UIColor *color = [UIColor colorWithHexString:@"#4C4C50"];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:textField.placeholder attributes:
    @{NSForegroundColorAttributeName:color}];
    textField.attributedPlaceholder = attrString;
}

//html图片屏幕适配
+(NSString *)autoFitHtml:(NSString *)content{
    NSMutableString *headHtml = [[NSMutableString alloc] initWithCapacity:0];
    [headHtml appendString : @"<html>" ];
    
    [headHtml appendString : @"<head>" ];
    
    [headHtml appendString : @"<meta charset=\"utf-8\">" ];
    
    [headHtml appendString : @"<meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=false\" />" ];
    
    [headHtml appendString : @"<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />" ];
    
    [headHtml appendString : @"<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />" ];
    
    [headHtml appendString : @"<meta name=\"black\" name=\"apple-mobile-web-app-status-bar-style\" />" ];
    
    //设置行间距和字体
    [headHtml appendString : @"<style>body{margin:0;background-color:transparent;font:16px;line-height: 25px;Custom-Font-Name}</style>"];
    
    //适配图片宽度，让图片宽度等于屏幕宽度
    //[headHtml appendString : @"<style>img{width:100%;}</style>" ];
    //[headHtml appendString : @"<style>img{height:auto;}</style>" ];
    
    //适配图片宽度，让图片宽度最大等于屏幕宽度
    //    [headHtml appendString : @"<style>img{max-width:100%;width:auto;height:auto;}</style>"];
    
    
    //适配图片宽度，如果图片宽度超过手机屏幕宽度，就让图片宽度等于手机屏幕宽度，高度自适应，如果图片宽度小于屏幕宽度，就显示图片大小
    [headHtml appendString : @"<script type='text/javascript'>"
     "window.onload = function(){\n"
     "var maxwidth=document.body.clientWidth;\n" //屏幕宽度
     "for(i=0;i <document.images.length;i++){\n"
     "var myimg = document.images[i];\n"
     "if(myimg.width > maxwidth){\n"
     "myimg.style.width = '100%';\n"
     "myimg.style.height = 'auto'\n;"
     "}\n"
     "}\n"
     "}\n"
     "</script>\n"];
    
    [headHtml appendString : @"<style>table{width:100%;}</style>" ];
    [headHtml appendString : @"<title>webview</title>" ];
    NSString *bodyHtml;
    bodyHtml = [NSString stringWithString:headHtml];
    bodyHtml = [bodyHtml stringByAppendingString:content];
    return bodyHtml;
//    return [NSString stringWithFormat:@"<html><head><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><style>*{ width: 100%%; margin: 0; padding: 0 3; box-sizing: border-box;} img{ width: 100%%;}</style></head><body>%@</body></html>", self];
}


+(void)commitButtonStyle:(UIButton *)btn{
    if(btn){
        UIImage *normalImage = [UIImage imageWithColor:kColorMain];
        UIImage *disableImage = [UIImage imageWithColor:[UIColor colorWithHexString:@"#666666"]];
        [btn setBackgroundImage:normalImage forState:UIControlStateNormal];
        [btn setBackgroundImage:disableImage forState:UIControlStateDisabled];
        btn.backgroundColor = nil;
    }
}


//阅读量显示规则
+(NSString *)readCountFormat:(NSString *)readCount{
    NSString *rtn;
    if(readCount.integerValue > 10000){
        rtn = [NSString stringWithFormat:@"%ldw",readCount.integerValue/10000];
    }else{
        rtn = readCount;
    }
    return rtn;
}


+(UIImage *)coverImageForNetVideo:(NSURL *)url{
    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:urlAsset];

    imageGenerator.appliesPreferredTrackTransform = YES;    // 截图的时候调整到正确的方向

    CMTime time = CMTimeMakeWithSeconds(0, 30);   // 1.0为截取视频1.0秒处的图片，30为每秒30帧

    CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:nil error:nil];

    UIImage *image11 = [UIImage imageWithCGImage:cgImage];
    return image11;
}




+(UIImage *)coverImageForLocalCache:(NSString *)url{
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    NSString* key = [manager cacheKeyForURL:[JMCommonMethod imageUrlWithPath:url]];
    SDImageCache* cache = [SDImageCache sharedImageCache];
    UIImage *cacheImg = [cache imageFromDiskCacheForKey:key];
    return cacheImg;
}


NSString *serviceUrlWith(NSString *url){
    return [NSString stringWithFormat:@"%@%@",serviceUrl(),url];
}
NSString* h5Url(NSString *ss){
    return serviceUrlWith([NSString stringWithFormat:@"h5?sessionId=%@&%@",JMProjectManager.sharedJMProjectManager.loginUser.sessionId,ss]);
}
NSString* serviceUrl(){
#if DEBUG
    return @"http://47.117.39.82";

#else
    return @"https://api.loanmarket.mx";

#endif
}
NSString* BasePostRequestUrl(NSString * url){
    return [NSString stringWithFormat:@"%@/app-loanmarket-api%@",serviceUrl(),url];
}
+(void)pushWebviewWithUrl:(NSString *)urlString andTitle:(NSString *)title{
    JMGlobalHtmlVC *vc = JMGlobalHtmlVC.new;
    vc.url = urlString;
    [UIWindow.jm_currentViewController.navigationController pushViewController:vc animated:YES];
    delayOperation(0.2, ^{
        vc.TitleLabel = title;
    });
}
+(void)presentWebviewWithUrl:(NSString *)urlString andTitle:(NSString *)title{
    JMGlobalHtmlVC *vc = [[JMGlobalHtmlVC alloc]init];
    vc.url = urlString;
    vc.titleString = title;
    if([urlString containsString:loginLoanAgreement]){
        [self uploadStatistics:@"Agreement" actionType:@"Enter" parameters:@{@"type":@"Loan"}];
    }
    if([urlString containsString:loginPrivacyAgreement]){
        [self uploadStatistics:@"Agreement" actionType:@"Enter" parameters:@{@"type":@"Privacy"}];
    }
    if([urlString containsString:LoginRegistrationAgreement]){
        [self uploadStatistics:@"Agreement" actionType:@"Enter" parameters:@{@"type":@"Register"}];
    }
    if([urlString containsString:@"credit-report"]){
        [self uploadStatistics:@"CreditReport" actionType:@"Enter" parameters:nil];
    }
    [UIWindow.jm_currentViewController.navigationController pushViewController:vc animated:YES];

}
NSString* fPinUrl(NSString* url) {
    return [NSString stringWithFormat:@"%@/%@/%@",serviceUrl(),@"gebao",url];
}
NSString* bundleVersion() {
    NSString *bundleVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey];
    return bundleVersion;
}
NSString* loginUserHeadImgUrlString(){
    return [JMCommonMethod pinImagePath:JMProjectManager.sharedJMProjectManager.loginUser.headUrl];
}
NSURL* loginUserHeadImgURL(){
    return [NSURL URLWithString:[JMCommonMethod pinImagePath:JMProjectManager.sharedJMProjectManager.loginUser.headUrl]];
}
+(void)loginSuccessWithDict:(NSDictionary *)dict{
    delayOperation(0, ^{
        RDVTabBarController *tabbarVC =[[SuperTabBarViewController alloc] init];
        [UIApplication sharedApplication].keyWindow.rootViewController = tabbarVC;
    });
}

+(void)openFico{
    JMLoginUserModel *user = JMProjectManager.sharedJMProjectManager.loginUser;
    NSString *creditUrl;
    NSString *title;
    
    creditUrl =[NSString stringWithFormat:@"%@/app-loanmarket-h5-creditreport/#/fico?phone=%@&userId=%@",serviceUrl(),user.phone,user.userId];
    title = @"My FICO";
    [JMCommonMethod uploadStatistics:@"CreditReport" actionType:@"Enter" parameters:nil];
    
   
    JMGlobalHtmlVC *vc = JMGlobalHtmlVC.new;
    vc.url = creditUrl;
    vc.titleString =title;
    [UIWindow.jm_currentViewController.navigationController pushViewController:vc animated:YES];
}
+(void)openCloudun{
    JMLoginUserModel *user = JMProjectManager.sharedJMProjectManager.loginUser;
    NSString *creditUrl;
    NSString *title;
    creditUrl =[NSString stringWithFormat:@"%@/app-loanmarket-h5-creditreport/#/cloudun?phone=%@&userId=%@",serviceUrl(),user.phone,user.userId];
    title = @"My Cloundun";
    [JMCommonMethod uploadStatistics:@"CreditReport" actionType:@"Enter" parameters:nil];
    
    JMGlobalHtmlVC *vc = JMGlobalHtmlVC.new;
    vc.url = creditUrl;
    vc.titleString = @"";
    [UIWindow.jm_currentViewController.navigationController pushViewController:vc animated:YES];
}
+(void)openFAQ{
    JMLoginUserModel *user = JMProjectManager.sharedJMProjectManager.loginUser;
    NSString *creditUrl;
    NSString *title;
    
    creditUrl = [NSString stringWithFormat:@"%@/app-loanmarket-h5-faq/#/FAQ?token=%@&packageName=%@",serviceUrl(),user.token,bundleId];
    [JMCommonMethod uploadStatistics:@"FAQ" actionType:@"Enter" parameters:nil];
    
    JMGlobalHtmlVC *vc = JMGlobalHtmlVC.new;
    vc.url = creditUrl;
    vc.titleString =title;
    [UIWindow.jm_currentViewController.navigationController pushViewController:vc animated:YES];
}

+ (void)uploadStatistics:(NSString *)pageName actionType:(NSString *)actionType parameters:(NSDictionary *)parameters {
    
    NSString *extInfo = @"";
    NSArray *productAndRanks = @[];
    NSString *type = @"";
    if (parameters != nil) {
        extInfo = [parameters mj_JSONString];
    }

    JMLoginUserModel *user = [JMProjectManager sharedJMProjectManager].loginUser;
    JMAppConfig *config = [JMProjectManager sharedJMProjectManager].appConfig;
    NSMutableDictionary *dic = @{
        @"action": actionType,
        @"adid": config.adid?config.adid:@"",
        @"extInfo": extInfo?extInfo:@"",
        @"pageName": pageName?pageName:@"",
        @"productId": @"",
        @"userRandomKey": user.randomKey
    };
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/common/user-behavior-record") params:dic success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        
        NSLog(@"❗️❗️❗️❗️❗️❗️❗️❗️打点上传成功; 参数: %@❗️❗️❗️❗️❗️❗️❗️", dic.description);
    } fail:^(NSString * _Nonnull errorMsg) {
        NSLog(@"❎❎❎❎❎❎❎打点上传失败; 参数: %@; error info: %@❎❎❎❎❎❎❎", dic.description, errorMsg);
    }];
}
+(void)userBehaviorTrack:(NSString *)pageName FeatureName:(NSString *)featureName Action:(track_Action)action{
    
    NSArray *typeArr = @[@"button",@"page",@"input",@"select"];
    NSArray *actionArr = @[@"BUTTON_CLICK",@"ENTER",@"OUT",@"GET_FOCUS",@"LOST_FOCUS",@"INPUT",@"PARSE",@"GET_FOCUS",@"LOST_FOCUS"];
    NSString *typeStr = @"";

    NSString *actionStr = actionArr[action];
    
    if (action == BUTTON_CLICK) {
        typeStr = typeArr[0];
    }
    if (action==ENTER || action ==OUT) {
        typeStr = typeArr[1];
    }
    
    if (action==GET_FOCUS || action ==LOST_FOCUS || action ==INPUT || action ==PARSE) {
        typeStr = typeArr[2];
    }
    if (action==SEL_GET_FOCUS || action ==SEL_LOSE_FOCUS ) {
        typeStr = typeArr[3];
    }
    
    JMLoginUserModel *user = [JMProjectManager sharedJMProjectManager].loginUser;
    JMAppConfig *config = [JMProjectManager sharedJMProjectManager].appConfig;
    NSDictionary *dict = @{@"gwUserBehaviorTrackRecordReq":@{@"deviceNo":user.deviceNo}};
   
    NSString *finalUrl = [NSString stringWithFormat:@"%@/%@/%@/%@/%@",BasePostRequestUrl(@"/api/user-behavior-track/record"),pageName,featureName,typeStr,actionStr];
    
    [[JMBaseRequest sharedInstance] requestBasePost:finalUrl params:dict success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        
        NSLog(@"✅✅✅✅✅✅✅✅埋点成功; 参数: %@✅✅✅✅✅✅✅✅", finalUrl);
    } fail:^(NSString * _Nonnull errorMsg) {
        NSLog(@"❌❌❌❌❌❌❌❌埋点失败; 参数: %@; error info: %@❌❌❌❌❌❌❌❌", finalUrl, errorMsg);
    }];
}

+(void)addRiskControlTracking:(NSString *)sceneType parameters:(NSDictionary *)parameters{
    JMLoginUserModel *user = [JMProjectManager sharedJMProjectManager].loginUser;
    JMAppConfig *config = [JMProjectManager sharedJMProjectManager].appConfig;
    NSString *endTime = @"";
    endTime =  @((NSInteger) [[NSDate new] timeIntervalSince1970] * 1000).stringValue;

    NSString *startTime = @"";
    if (parameters) {
        startTime = parameters[@"startTime"];
    }
    NSMutableDictionary *dic = @{
        @"adid": config.adid?config.adid:@"",
        @"sceneType":sceneType?sceneType:@"",
        @"deviceNo":user.deviceNo?user.deviceNo:@"",
        @"endTime": endTime,
        @"latitude": user.latitude.length?user.latitude:@"",
        @"longitude": user.longitude?user.longitude:@"",
        @"packageName": bundleId,
        @"startTime": @(startTime.integerValue),
        @"userId": user.userId?user.userId:@"",
        @"userRandomKey":user.randomKey
    };
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/penetrador/amortiguado/ferrificareis") params:dic success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        
        NSLog(@"😁😁😁😁😁😁😁😁😁😁😁埋点上传成功; 参数: %@😁😁😁😁😁😁😁😁😁😁😁😁😁😁😁😁", dic.description);
    } fail:^(NSString * _Nonnull errorMsg) {
        NSLog(@"❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️埋点上传失败; 参数: %@; error info: %@❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️❗️", dic.description, errorMsg);
    }];

}
@end
